package com.xunji.xunji.module.trace.controller;

import android.database.MatrixCursor;

import com.huanxiao.util.CtxHelper;
import com.qiniu.android.http.PostArgs;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.xunji.xunji.controller.QiniuManager;
import com.xunji.xunji.db.dao.TraceImageDao;
import com.xunji.xunji.module.trace.dao.TraceImage;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Paul on 2017/3/2.
 */

public class UploadManger {

    private static UploadManger instance;


    private List<TraceImage> traceImageList = new ArrayList<>();


    private int currentPosition = 0;
    private boolean isUploading = false;
    private IUploadFinishListener mListener;
    private TraceImageDao traceImageDao;


    public UploadManger(List<TraceImage> list, IUploadFinishListener listener) {
        this.traceImageList = list;
        this.mListener = listener;
        this.traceImageDao = new TraceImageDao(CtxHelper.getApp());
    }

    /**
     * 上传
     */

    public void upload() {
        if (!isUploading) {
            File file = null;

            for (int i = 0; i < traceImageList.size(); i++) {

                if (!traceImageList.get(i).isUploaded()) {
                    file = new File(traceImageList.get(i).getImagePaths());
                    currentPosition = i;
                    break;
                }
            }
            QiniuManager.getInstance().upload(file, new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    isUploading = false;
                    if (info.isOK()) {
                        traceImageList.get(currentPosition).setImageUrl(key);
                        traceImageList.get(currentPosition).setUploaded(true);

                        //更新
                        traceImageDao.update(traceImageList.get(currentPosition));
                        if (currentPosition == traceImageList.size() - 1) {
                            mListener.onItemFinish(currentPosition, key);
                            mListener.onUploadFinish();
                        } else {
                            mListener.onItemFinish(currentPosition, key);
                            upload();
                        }
                    } else {
                        //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        mListener.onUploadFinish();
                    }



                }
            });
        }
    }


    public interface IUploadFinishListener {
        /**
         * 全部上传完成
         */
        void onUploadFinish();

        /**
         * 单个完成
         *
         * @param position
         */
        void onItemFinish(int position, Object object);

        /**
         * 失败
         */
        void onFailed();
    }


}
